package com.chenfan.common.extension.context;

import com.chenfan.common.exception.BusinessException;
import com.chenfan.common.exception.ResultState;
import com.chenfan.common.vo.UserVO;
import com.chenfan.infra.context.TenantContextHolder;
import org.apache.commons.lang3.ObjectUtils;

import java.util.Objects;
import java.util.Optional;

/**
 * Created by mbji on 2018/11/14.
 * @author mbji
 * @date 2018/11/14.
 */
public class UserContextHolder {

    public static UserVO getUserVo() {
        return TraceContextHolder.<UserVO>getOptional(TraceContext.CURRENT_USER).orElse(null);
    }
    
    public static UserVO getUserVo(ResultState resultState) {
        return TraceContextHolder.<UserVO>getOptional(TraceContext.CURRENT_USER).orElseThrow(() -> new BusinessException(resultState));
    }

    public static Long getUserId(){
        UserVO userVO = getUserVo();
        if(userVO != null){
            return userVO.getUserId();
        }
        return null;
    }

    public static Long getTenantId(){
        UserVO userVO = getUserVo();
        if(userVO != null){
            return userVO.getTenantId();
        }
        return TraceContextHolder.<Long>getOptional(TraceContext.TENANT_ID).orElse(TenantContextHolder.getTenantId());
    }

    public static Long defaultTenantId(){
        return ObjectUtils.defaultIfNull(getTenantId(), -1L);
    }

    public static Long defaultUserId() {
        return ObjectUtils.defaultIfNull(getUserId(), -1L);
    }

    public static Long getCompanyId(){
        UserVO userVO = getUserVo();
        if(userVO != null){
            return userVO.getCompanyId();
        }
        return null;
    }

    public static Long getDepartmentId(){
        UserVO userVO = getUserVo();
        if(userVO != null){
            return userVO.getDepartmentId();
        }
        return null;
    }

    public static String getUserName(){
        UserVO userVO = getUserVo();
        if(userVO != null){
            return userVO.getRealName();
        }
        return null;
    }

    public static String getDefaultUserName(){
        return Optional.ofNullable(getUserName()).orElse("admin");
    }


    public static String getToken() {
        UserVO userVO = getUserVo();
        if(userVO != null){
            return userVO.getToken();
        }
        return TraceContextHolder.<String>getOptional(TraceContext.TOKEN).orElse(null);
    }

    public static boolean isCurrentUser(Long userId) {
        Long currentUserId = UserContextHolder.getUserId();
        return Objects.nonNull(currentUserId) && currentUserId.equals(userId);
    }
}
